package com.yuhanxun.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

public class DealFile {
    /**
     * @param file install apk
     * @param con
     */
    public static void openFile(File file, Context con) { 
        // TODO Auto-generated method stub 
        Intent intent = new Intent(); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        intent.setAction(Intent.ACTION_VIEW); 
        intent.setDataAndType(Uri.parse("file://" + file), 
                        "application/vnd.android.package-archive"); 
        con.startActivity(intent); 
    }
    
	public static boolean createFile(File file) throws IOException {
		if(! file.exists()) {
			makeDir(file.getParentFile());
		}
		return file.createNewFile();
	}
	/**
	 * Enhancement of java.io.File#mkdir()
	 * Create the given directory . If the parent folders don't exists, we will create them all.
	 * @see java.io.File#mkdir()
	 * @param dir the directory to be created
	 */
	public static void makeDir(File dir) {
		if(! dir.getParentFile().exists()) {
			makeDir(dir.getParentFile());
		}
		dir.mkdir();
	}
    public static final boolean copyFile(String srcFilePath, String destFilePath) {
		boolean bOk = false;
		FileInputStream fin = null;
		FileOutputStream fout = null;
		FileChannel srcChannel = null;
		FileChannel dstChannel = null;
		try {
			fin = new FileInputStream(srcFilePath);
			fout = new FileOutputStream(destFilePath);
			// Create channel on the source
			srcChannel = fin.getChannel();

			// Create channel on the destination
			dstChannel = fout.getChannel();

			// Copy file contents from source to destination
			dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
			bOk = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// Close the channels
			close(srcChannel);
			close(dstChannel);
			close(fin);
			close(fout);
		}
		return bOk;
	}

	public static final boolean deleteFile(String delFilePath) {
		boolean bOk = false;
		try {
			File file = new File(delFilePath);
			if (file.exists() && file.isFile()) {
				bOk = file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bOk;
	}

	public static final boolean recoverFile(String toFilePath,
			String bakFilePath) {
		boolean bOk = false;
		try {
			File bak = new File(bakFilePath);
			if (bak.exists() && bak.isFile()) {
				File to = new File(toFilePath);
				if (to.exists() && to.isFile()) {
					to.delete();
				}
				bOk = bak.renameTo(to);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bOk;
	}

	/**
	 * @param toFilePath 被覆盖路径
	 * @param bakFilePath 源路径
	 * 
	 * @return 
	 */
	public static final boolean recoverFile_move(String toFilePath,
			String bakFilePath) {
		boolean bOk = false;
		File bak = new File(bakFilePath);
		if (bak.exists()) {
			File to = new File(toFilePath);
			if (to.exists()) {
				to.delete();
			}
			DealFile.copyFile(bakFilePath, toFilePath);
			deleteFile(bakFilePath);
			bOk = true;
		} else {
			System.out.println("源文件不存在，无法覆盖");
			return bOk;
		}
		return bOk;

	}

	// LiuJun: useless in this project.
	// // create a file param: file name , file content
	// public static boolean savedata(Context mctx, String fname, String
	// content) {
	// OutputStream os = null;
	// DataOutputStream dos = null;
	// boolean ret = false;
	// try {
	// mctx.getFileStreamPath(fname);
	// // openFileOutStream() -- get the file stream
	// os = mctx.openFileOutput(fname, Context.MODE_PRIVATE);
	// dos = new DataOutputStream(os);
	// dos.writeUTF(content);
	// ret = true;
	// } catch (Exception e) {
	// e.printStackTrace();
	// } finally {
	// close(dos);
	// close(os);
	// }
	// return ret;
	// }
	//
	// // get the file content param: file name
	// public static String loaddata(Context mctx, String fname) {
	// String str = "";
	// InputStream is = null;
	// DataInputStream dis = null;
	// try {
	// is = mctx.openFileInput(fname);
	// dis = new DataInputStream(is);
	// str = dis.readUTF();
	// } catch (Exception e) {
	// e.printStackTrace();
	// } finally {
	// close(dis);
	// close(is);
	// }
	// return str;
	// }
	// public static final String getCfgProp(String filepath, String key)
	// {
	// return "";
	// }

	// 删除文件夹
	// param folderPath 文件夹完整绝对路径

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public static boolean delAllFile(String pathDir) {
		boolean flag = false;
		File file = new File(pathDir);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (pathDir.endsWith(File.separator)) {
				temp = new File(pathDir + tempList[i]);
			} else {
				temp = new File(pathDir + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(pathDir + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(pathDir + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}
	
	public static void close(Closeable s) {
		try {
			if (s != null) {
				s.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String ReadTxtFile(String strFilePath)
    {
        String path = strFilePath;
        String content = ""; //文件内容字符串
            //打开文件
            File file = new File(path);
            //如果path是传递过来的参数，可以做一个非目录的判断
            if (file.isDirectory())
            {
                Log.d("TestFile", "The File doesn't not exist.");
            }
            else
            {
                try {
                    InputStream instream = new FileInputStream(file); 
                    if (instream != null) 
                    {
                        InputStreamReader inputreader = new InputStreamReader(instream);
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line;
                        //分行读取
                        while (( line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }                
                        instream.close();
                    }
                }
                catch (java.io.FileNotFoundException e) 
                {
                    Log.d("TestFile", "The File doesn't not exist.");
                } 
                catch (IOException e) 
                {
                     Log.d("TestFile", e.getMessage());
                }
            }
            return content;
    }
	
	/**
	 * 
	 * @param AppContext
	 * @param desFilePath
	 * @param rcId
	 * @return 0:已经存在 1:复制 2:Exception
	 */
	public static final int copyFileFromRaw(Context AppContext,
			String desFilePath, int rcId) {
		int ret = 0;
		// 如果在目录中不存在db文件，则从res\raw目录中复制这个文件到目录中
		if (!(new File(desFilePath)).exists()) {
			// 获得db文件的InputStream对象
			InputStream is = AppContext.getResources().openRawResource(rcId);
			FileOutputStream fos = null;
			byte[] buffer = new byte[8192];
			try {
				fos = new FileOutputStream(desFilePath);
				int count = 0;
				// 开始复制db文件
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				ret = 1;
			} catch (Exception e) {
				ret = 2;
				e.printStackTrace();
			} finally {
				close(fos);
				close(is);
			}

			// copy结束后设置数据库文件访问属性
			try {
				Runtime run = Runtime.getRuntime();
				String cmd = "chmod 666 " + desFilePath;
				Process p = run.exec(cmd, null, null);
				p.waitFor();// 等待进程结束（设回同步标志），否则下次执行可能会阻塞
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return ret;
	}
}
